<?php

/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AuthenticatedApp extends AppModel {

    /**
     * Authenticates an app based on the $app_id and $app_key provided
     * 
     * @param mixed $app_id
     * @param mixed $app_key
     * @return boolean
     */
    public function authenticate($app_id, $app_key) {
        $app = $this->find('first', array(
            'conditions' => array('AuthenticatedApp.app_id' => $app_id,'AuthenticatedApp.status' => 'active'),
            'recursive' => -1
        ));
        
        // if we could not find the app by id
        if( !$app ) {
            return false;
        }
        
        // remake the hash used in storing the record
        $app_key_hash = md5($app_key . $app['AuthenticatedApp']['app_key_salt']);
        
        // if new hash and stored hash don't match, return
        if( $app_key_hash != $app['AuthenticatedApp']['app_key'] ) {
            return false;
        }
        
        // if all is okay
        return true;
    }
}
